package com.knife.bbs.action;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import org.apache.commons.fileupload.FileItem;

import com.knife.util.CommUtil;
import com.knife.util.FileUtil;
import com.knife.web.ActionContext;
import com.knife.web.Globals;
import com.knife.web.IWebAction;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.bbs.business.ActiveUser;
import com.knife.bbs.business.BBSUserService;
import com.knife.bbs.business.SkinService;
import com.knife.bbs.object.Skin;

/**
 * 
 * <p>
 * Title:处理上传程序
 * </p>
 * <p>
 * Description:把上传来的数据保存到相应的目录.
 * </p>
 */
public class UploadAction implements IWebAction {
	
	private SkinService skinService = SkinService.getInstance();
	
	public String skin="default";
	
	public Page execute(WebForm form, Module module) throws Exception {
		Skin myskin=skinService.getUsedSkin();
		if(myskin!=null){
			skin=myskin.getSkin();
		}

		String types = CommUtil.null2String(form.get("types")).trim();

		java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
				"yyyyMMdd");
		ActiveUser user = (ActiveUser) ActionContext.getContext().getSession()
				.getAttribute("bbsuser");
		// 直接通过form取得表单中存的文件,若有文件则执行相应的操作
		if (form.getFileElement().keySet().size() > 0) {
			if (user != null)// 只有注册用户才能上传
			{
				
					Iterator it = form.getFileElement().keySet().iterator();
					if (it.hasNext()) {
						String fieldName = (String) it.next();
						FileItem file = (FileItem) form.getFileElement().get(
								fieldName);
						String clientName = file.getName();
						String parentDir;
						if (types.equals("doc")) {
							parentDir = "doc/" + dateFormat.format(new Date());
						} else
							parentDir = "user/" + user.getUserName();
			       if (FileUtil.isImgageFile(clientName)||FileUtil.isAttacheFile(clientName)) {//用户只能传图片及定义的附件文件						
							String filePath = Globals.APP_BASE_DIR
									+ "bbs/upfile/" + parentDir + "/";
							try {
								File fdir = new File(filePath);
								if (!fdir.exists())
									fdir.mkdirs();
								String fileName = (types.equals("doc") ? (CommUtil
										.getRandString(10) + clientName
										.substring(clientName.lastIndexOf(".")))
										: clientName.substring(clientName
												.lastIndexOf("\\") + 1));
								String fullFileName = "/bbs/upfile/"
										+ parentDir + "/" + fileName;
								form.addResult("fileName", fullFileName);
								file.write(new File(filePath + fileName));
							} catch (Exception e) {
								System.out.println("文件上传错误！" + e);
							}

						} else {
							form.addResult("msg", "只能上传图片及附件文件！");
						}
					}
				
			} else {
				form.addResult("msg", "您没有登录，不能上传图片！");
			}
		}
		return module.findPage("/"+skin+"/",module.getDefaultPage());
	}
}
